package com.techyuan.intellij.tomcat.setting;


import com.intellij.ide.browsers.WebBrowser;
import com.intellij.ide.browsers.WebBrowserManager;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.ui.ComboboxSpeedSearch;
import com.intellij.ui.SortedComboBoxModel;
import java.util.Collection;
import java.util.List;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class WebBrowserComboBox extends ComboBox<WebBrowser> {
    private final SortedComboBoxModel<WebBrowser> myModel;
    private boolean myAllowEmptySelection;

    public WebBrowserComboBox() {
        this(new SortedComboBoxModel(WebBrowsersAlphaComparator.INSTANCE));
    }

    private WebBrowserComboBox(SortedComboBoxModel<WebBrowser> model) {
        super(model);
        this.myModel = model;
        ComboboxSpeedSearch search = new ComboboxSpeedSearch(this) {
            protected String getElementText(Object element) {
                if (element instanceof WebBrowser) {
                    return ((WebBrowser)element).getName();
                } else {
                    return element == null ? "" : super.getElementText(element);
                }
            }
        };
        this.setRenderer(new WebBrowserListCellRenderer());
    }

    public void allowEmptySelection(@NotNull String emptySelectionText) {
        this.myAllowEmptySelection = true;
        this.myModel.add(null);
        this.setRenderer(new WebBrowserListCellRenderer(emptySelectionText));
    }

    public void setWebBrowsers(@NotNull Collection<WebBrowser> webBrowsers) {
        this.myModel.setAll(webBrowsers);
        if (this.myAllowEmptySelection) {
            this.myModel.add(null);
        }

    }

    public void fillWebBrowsers() {
        List<WebBrowser> allBrowsers = WebBrowserManager.getInstance().getActiveBrowsers();
        setWebBrowsers(allBrowsers);
    }

    public void setSelectedWebBrowser(@Nullable WebBrowser webBrowser) {
        this.myModel.setSelectedItem(webBrowser);
    }

    @Nullable
    public WebBrowser getSelectedWebBrowser() {
        return (WebBrowser)this.myModel.getSelectedItem();
    }
}
